package com.vivz.guess.what;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AllPreferenceFragment extends PreferenceFragment {

	private static final OnPreferenceChangeListener ON_PREFERENCE_CHANGE = new SummaryToValuePreferenceChangeListener();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Load the preferences from an XML resource
		addPreferencesFromResource(R.xml.pref_all);

		// General Settings
		bindPreferenceSummaryToValue(findPreference("example_text"));
		bindPreferenceSummaryToValue(findPreference("example_list"));

		// Notification Settings
		bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));

		// Data sync settings
		bindPreferenceSummaryToValue(findPreference("sync_frequency"));

	}

	/**
	 * Binds a preference's summary to its value. More specifically, when the preference's value is changed, its summary
	 * (line of text below the preference title) is updated to reflect the value. The summary is also immediately
	 * updated upon calling this method. The exact display format is dependent on the type of preference.
	 * 
	 * @see #sBindPreferenceSummaryToValueListener
	 */
	private void bindPreferenceSummaryToValue(Preference preference) {
		// Set the listener to watch for value changes.
		preference.setOnPreferenceChangeListener(ON_PREFERENCE_CHANGE);

		// Trigger the listener immediately with the preference's current value.
		Context context = preference.getContext();
		SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		String value = defaultSharedPreferences.getString(preference.getKey(), "");
		ON_PREFERENCE_CHANGE.onPreferenceChange(preference, value);
	}

}
